package com.example.oneMachineLock;

import org.openjdk.jol.info.ClassLayout;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * create by mwh 2021-12-11
 *
 * synchronied锁
 **/

@RestController
@RequestMapping("/syn")
public class SynLock {

    /**
     * 保证线程syn内部的方法都是串行的，线程间不能穿插
     * 本身一个线程是按照前-》后执行的，本身是线性的
     *
     * 并发下（jmeter测试一个接口1秒请求10次或者代码写多线程execute.new多线程或者thread.start）
     * 未加syn前：
     * thread1--test1
     * thread2--test1
     * thread3--test1
     * thread1--test2
     * thread2--test2
     * thread3--test2
     * 加syn前：
     * thread1--test1
     * thread1--test2
     * thread1--test3
     * thread2--test1
     * thread2--test2
     * thread2--test3
     * @throws InterruptedException
     *
     * markword   classlayout打印对象信息
     * java.lang.Integer object internals:
     *  OFFSET  SIZE   TYPE DESCRIPTION                               VALUE
     *       0     4        (object header)                           48 ce 4d 23 (01001000 11001110 01001101 00100011) (592301640)
     *       4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
     *       8     4        (object header)                           67 22 00 f8 (01100111 00100010 00000000 11111000) (-134208921)
     *      12     4    int Integer.value                             0
     * Instance size: 16 bytes
     * Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
     *
     */
    @GetMapping("/test")
    public void test() throws InterruptedException {
        Integer i =0;
        synchronized (i){
            test1();
            test2();
            test3();
            System.out.println(ClassLayout.parseInstance(i).toPrintable());
        }

    }

    private void test3() {
        System.out.println(Thread.currentThread().getName()+"snc test3");
    }

    private void test2() {
        System.out.println(Thread.currentThread().getName()+"snc test2");
    }

    private void test1() throws InterruptedException {
        System.out.println(Thread.currentThread().getName()+"snc test1");
        Thread.sleep(3000);
    }


}
